package com.frxuexi.sign.view

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.navigation.NavHostController
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.UiState
import com.frxuexi.sign.R
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


lateinit var mapView: MapView
lateinit var baiduMap: BaiduMap
lateinit var mLocationClient: LocationClient
lateinit var timer: Timer

@Composable
fun SignPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {
    start()
    val kv = MMKV.defaultMMKV()
    var currentTime by remember {
        mutableStateOf(vm.toTime(System.currentTimeMillis()))
    }
    var btnText by remember {
        mutableStateOf("签到")
    }

    var startTime by remember {
        mutableStateOf("还未打卡")
    }
    var endTime by remember {
        mutableStateOf("还未打卡")
    }
    var isEnable by remember {
        mutableStateOf(true)
    }
    var startImg by remember {
        mutableStateOf(R.drawable.ic_action_qd)
    }
    var endImg by remember {
        mutableStateOf(R.drawable.ic_action_qd)
    }

    var isShowStart by remember {
        mutableStateOf(false)
    }

    var isShowEnd by remember {
        mutableStateOf(false)
    }

    val lifecycleOwner = LocalLifecycleOwner.current
    LaunchedEffect(key1 = "", block = {
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                currentTime = vm.toTime(System.currentTimeMillis())
            }, 0, 1000)
        }

        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("打卡成功")
                        navHostController.popBackStack()
                    }

                    else -> {}
                }
            }
        }

        launch {
            val signTime = kv.decodeLong("sign", 0L)
            //签到过
            if(signTime!=0L){
                val date = vm.toDate(signTime)
                //今天签到过
                if(date==vm.toDate(System.currentTimeMillis())){
                    startTime=vm.toTime(signTime)
                    btnText="签退"
                    isShowStart=true
                    if(startTime>="09:00:00"){//迟到
                        startImg=R.drawable.ic_action_cd
                        startTime=startTime+"(迟到)"
                    }
                }
                val soutTime = kv.decodeLong("sout", 0L)
                if(soutTime!=0L && vm.toDate(soutTime) == vm.toDate(System.currentTimeMillis())){
                    //说明今天签退过
                    isShowEnd=true
                    endTime=vm.toTime(soutTime)
                    isEnable=false
                    if(vm.toTime(soutTime)<="18:00:00"){//迟到
                        endImg=R.drawable.ic_action_cd
                        endTime=endTime+"(早退)"
                    }
                }

            }
        }
    })

    DisposableEffect(key1 = "", effect = {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    Log.i("===", "oncreate")
                }

                Lifecycle.Event.ON_RESUME -> {
                    Log.i("===", "ON_RESUME")
                }

                Lifecycle.Event.ON_START -> {
                    Log.i("===", "ON_START")
                }

                Lifecycle.Event.ON_PAUSE -> {
                    Log.i("===", "ON_PAUSE")
                }

                Lifecycle.Event.ON_STOP -> {
                    Log.i("===", "ON_STOP")
                }

                Lifecycle.Event.ON_DESTROY -> {
                    Log.i("===", "ON_DESTROY")
                }

                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            Log.i("===", "onDispose")
            lifecycleOwner.lifecycle.removeObserver(observer)
            timer.cancel()
            mLocationClient.stop();
            baiduMap.setMyLocationEnabled(false);
            mapView.onDestroy();
        }
    })
    Column {
        BaseTitle(
            navHostController = navHostController,
            title = "打卡",
            modifier = Modifier.padding(10.dp)
        )
        AndroidView(modifier = Modifier
            .fillMaxWidth()
            .height(260.dp), factory = {
            mapView = MapView(it)
            baiduMap = mapView.map
            baiduMap.isMyLocationEnabled = true
            mapView
        })
        Spacer(modifier = Modifier.height(10.dp))
        Row(
            Modifier
                .fillMaxWidth()
                .padding(20.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)
        ) {
            Column(
                modifier = Modifier
                    .weight(1f)
                    .background(
                        colorResource(id = com.frxuexi.lib_base.R.color.lightgray),
                        RoundedCornerShape(20.dp)
                    )
                    .padding(horizontal = 12.dp, 10.dp)
            ) {
                Text(text = "签到时间：9:00")
                Spacer(modifier = Modifier.height(8.dp))
                Row {
                    if(isShowStart) {
                        Image(
                            painter = painterResource(id = startImg),
                            contentDescription = ""
                        )
                    }
                    Text(text = startTime)
                }
            }

            Column(
                modifier = Modifier
                    .weight(1f)
                    .background(
                        colorResource(id = com.frxuexi.lib_base.R.color.lightgray),
                        RoundedCornerShape(20.dp)
                    )
                    .padding(10.dp)
            ) {
                Text(text = "签退时间：18:00")
                Spacer(modifier = Modifier.height(8.dp))
                Row {
                    if(isShowEnd) {
                        Image(
                            painter = painterResource(id = endImg),
                            contentDescription = ""
                        )
                    }
                    Text(text = endTime)
                }
            }
        }

        Spacer(modifier = Modifier.height(10.dp))
        Button(
            onClick = {
                val currentHour = currentTime.substring(0, 2).toInt()
                val currentTimeMillis = System.currentTimeMillis()
                if (btnText == "签到") {
                    startTime=currentTime
                    btnText="签退"
                    isShowStart=true
                    if(currentHour>=9){//迟到
                        startImg=R.drawable.ic_action_cd
                        startTime=currentTime+"(迟到)"
                    }
                    kv.encode("sign",currentTimeMillis)
                }else{
                    endTime=currentTime
                    isEnable=false
                    isShowEnd=true
                    if(currentHour<=18){//迟到
                        endImg=R.drawable.ic_action_cd
                        endTime=currentTime+"(早退)"
                    }
                    kv.encode("sout",currentTimeMillis)
                }
                val map = mutableMapOf<String, Any>()
                map["userId"]=1
                map["signTime"]=currentTimeMillis
                map["SignLat"]=kv.decodeFloat("latitude",0f)
                map["SignLong"]=kv.decodeFloat("longitude",0f)
                vm.sendIntent(SignIntent.sign(map))
            }, shape = CircleShape,
            enabled = isEnable,
            colors = ButtonDefaults.buttonColors(containerColor = colorResource(id = com.frxuexi.lib_base.R.color.blue)),
            modifier = Modifier
                .size(150.dp)
                .align(Alignment.CenterHorizontally)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(text = btnText, color = Color.White, fontSize = 22.sp)
                Spacer(modifier = Modifier.height(10.dp))
                Text(text = currentTime, color = Color.White, fontSize = 22.sp)
            }
        }

    }

}

fun start() {
    LocationClient.setAgreePrivacy(true)
    //定位初始化
    mLocationClient = LocationClient(BaseApp.context)
//通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps

    option.setCoorType("bd09ll") // 设置坐标类型

    option.setScanSpan(1000)

//设置locationClientOption
    mLocationClient.setLocOption(option)

//注册LocationListener监听器
    val myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
    mLocationClient.start()
}


class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mapView == null) {
            return
        }
        val latitude = location.latitude
        val longitude = location.longitude
        val kv = MMKV.defaultMMKV()
        kv.encode("latitude",latitude)
        kv.encode("longitude",longitude)

        //定位蓝点额外加的
        var ll = LatLng(latitude, longitude);
        val update = MapStatusUpdateFactory.newLatLngZoom(ll, 5f);
        baiduMap.animateMapStatus(update);

        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        baiduMap.setMyLocationData(locData)
    }
}